package test3;

public class Demo1 {
    public static void main(String[] args) {
        int[] root = new int[1000];
        root[0] = 1;
        root[1] = 1;
        root[2] = 2;
        root[3] = 0;
        root[4] = 0;
        root[5] = 4;
        root[6] = 5;
        String str = "/1/2";
        int[] son = {5, 3, 0};
        getTree(root, str, son);
        //输出root中不为 0 的
        for (int i = 0; i < root.length; i++) {
            if (root[i] != 0) {
                System.out.print(root[i] + ",");
            }
        }
    }

    //将数组转化成
    public static int[] getTree(int[] root, String str, int[] son) {
        //1.找到替换结点
        String[] nodes = str.split("\\/");// 0/1/2
        int flag = 1;
        //从第二层开始比较
        for (int i = 2; i < nodes.length; i++) {
            //比较他的左节点和右结点
            int left = root[2 * flag - 1];
            if (left == root[i]) {
                flag = 2 * flag - 1;
                continue;
            }
            int right = root[2 * flag];
            if (right == root[i]) {
                flag = 2 * flag;
                continue;
            }
        }
        //将 flag 的所有子节点删除
        dispose(flag, root);
        //将子树根节点放入进去，有点麻烦
        for (int i = 0; i < son.length; i++) {
            int pow = (int) Math.pow(2, i + 1);
            root[i + pow] = son[i];
        }
        return root;
    }

    static void dispose(int flag, int[] root) {
        if (root[flag] == 0) {
            return;
        } else {
            root[flag] = 0;
            //处理左边的
            dispose(2 * (flag + 1) - 1, root);
            //处理右边的
            dispose(2 * (flag + 1), root);
        }
    }
}
